﻿namespace UFIDA.U9C.Cust.ZL.BP.SOMBP
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Diagnostics;
    using System.Linq;
    using System.Text;
    using UFIDA.U9.CBO.SCM;
    using UFIDA.U9.PriceCal.PriceCalSV;
    using UFIDA.U9.SM.Ship;
    using UFIDA.U9.SM.SMBE.ShipPreShip;
    using UFIDA.U9.SM.SO;
    using UFIDA.U9.SM.SOModify;
    using UFSoft.UBF.AopFrame;
    using UFSoft.UBF.Transactions;
    using UFSoft.UBF.Util.Context;

    /// <summary>
    /// Operate partial 
    /// </summary>	
	public partial class Operate
    {
        internal BaseStrategy Select()
        {
            return new OperateImpementStrategy();
        }
    }

    #region  implement strategy	
    /// <summary>
    /// Impement Implement
    /// 
    /// </summary>	
    internal partial class OperateImpementStrategy : BaseStrategy
    {
        public OperateImpementStrategy() { }
        /// <summary>
        /// 销售订单变更单 审核后  更新出货单金额 、处理应收单
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public override object Do(object obj)
        {

            Operate bpObj = (Operate)obj;
            if (bpObj == null)
                throw new NotImplementedException("参数为空");
            try
            {
                SOModify soModify = SOModify.Finder.FindByID(bpObj.EntityID);
                if (soModify == null)
                {
                    return new ReturnDTO() { Code = 1, Message = "销售订单变更数据为空" };
                }
                var solines = soModify.SO.SOLines.OfType<SOLine>();

                var soModifylines = soModify.SOModifyLines.OfType<SOModifyLine>();

                var modifiedLines = soModifylines.Where(p => p.ModifyDataItem.Equals("FinallyPriceTC", StringComparison.OrdinalIgnoreCase));
                using (UBFTransactionScope scope = new UBFTransactionScope(TransactionOption.RequiresNew))
                {
                    try
                    {
                        //新逻辑：
                        //1、更新出货单金额 如果出货单返回已经立账不能调价 则进行红冲 红冲后再进行更新
                        //2、wanxin需求变更 原因：关账后 销售订单不能打开，无法做销售订单变更单，在销售订单客开按钮做红冲应收，这部分需要再更新出货单后再次生成应收单




                        //更新出货单 金额-数量
                        List<EntityBatchResultData> res = BusinessLogic.AdjustmentShiplinePrice(modifiedLines);
                        bool isred = false;
                        List<long> arhead = null;

                        if (res != null && res.Count > 0 && res[0].ErrorMessage.Contains("已经立账不能调价"))
                        {
                            isred = true;
                            arhead = BusinessLogic.RedAR(modifiedLines);
                            res = BusinessLogic.AdjustmentShiplinePrice(modifiedLines);//红冲过原应收单后 再次更新出货单金额
                        }

                        if (res != null && res.Count > 0 && !string.IsNullOrEmpty(res[0].ErrorMessage))
                        {
                            throw new Exception("变更出货单：" + res[0].ErrorMessage);
                        }

                        if (isred && arhead != null)
                        {//原有应收单则更新完数据后
                            //处理应收单 
                            BusinessLogic.AdjustmentAR(arhead, modifiedLines);
                        }
                        else
                        {
                            //查询对应销售订单有没有红冲的单据 如果有红冲单据则需要 重新生成应收单
                            //查询销售订单对应的被红冲的应收单 一张出货单->一张应收单 暂定取最新的一张应收单作为复制的单据
                            arhead = new List<long>();
                            string sql = $@"select max(a.DocNo),MAX(a.ID) arid, b.SrcBillLineID from AR_ARBillLine b inner join AR_ARBillHead a on a.id=b.ARBillHead 
inner join SM_Shipline c on b.SrcBillLineID=c.id
inner join SM_SOLine d on c.SOLinekey=d.id
inner join SM_SO e on e.id=d.so
where e.id='{soModify.SO.ID}' and b.RedFlushStatus=0
group by b.SrcBillLineID";
                            DataSet ds = new DataSet();
                            int result = UFSoft.UBF.Util.DataAccess.DataAccessor.RunSQL(UFSoft.UBF.Util.DataAccess.DataAccessor.GetConn(), sql, null, null, true, out ds);
                            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                            {
                                foreach (DataRow item in ds.Tables[0].Rows)
                                {
                                    arhead.Add(Convert.ToInt64(item["arid"]));
                                }
                                if (arhead.Count > 0)
                                {
                                    BusinessLogic.AdjustmentAR(arhead, modifiedLines);
                                }
                            }

                        }
                        scope.Commit();
                    }
                    catch (Exception ex)
                    {
                        scope.Rollback();
                        throw ex;
                    }
                }



            }
            catch (Exception ex)
            {
                return new ReturnDTO() { Code = 2, Message = ex.Message };
            }
            return new ReturnDTO() { Code = 0, Message = "成功" };
        }
    }

    #endregion


}